from typing import List
from .model import UserGroup
from ninja import Field, ModelSchema, Query, Router
from ninja.pagination import paginate
from utils.fu_crud import (
    ImportSchema,
    create,
    delete,
    export_data,
    import_data,
    retrieve,
    update,
)
from utils.fu_ninja import FuFilters, MyPagination

router = Router()


# 设置过滤字段
class Filters(FuFilters):
        
    name: str = Field(None, alias='name')    
    user_group: str = Field(None, alias='user_group')


# 设置请求接收字段
class UserGroupSchemaIn(ModelSchema):

    class Config:
        model = UserGroup
        model_exclude = ['create_datetime', 'update_datetime', 'belong_dept', 'modifier', 'creator', 'id']


# 设置响应字段
class UserGroupSchemaOut(ModelSchema):

    class Config:
        model = UserGroup
        model_fields = '__all__'


# 创建UserGroup
@router.post('/user_group', response=UserGroupSchemaOut)
def create_user_group(request, data: UserGroupSchemaIn):
    user_group = create(request, data, UserGroup)
    return user_group


# 删除UserGroup
@router.delete('/user_group/{id}')
def delete_user_group(request, id: int):
    delete(id, UserGroup)
    return {'success': True}


# 更新UserGroup
@router.put('/user_group/{id}', response=UserGroupSchemaOut)
def update_user_group(request, id: int, data: UserGroupSchemaIn):
    user_group = update(request, id, data, UserGroup)
    return user_group


# 获取UserGroup
@router.get('/user_group', response=List[UserGroupSchemaOut])
@paginate(MyPagination)
def list_user_group(request, filters: Filters = Query(...)):
    qs = retrieve(request, UserGroup, filters)
    return qs


# 导入
@router.get('/user_group/all/export')
def export_user_group(request):
    export_fields = ('name', 'user_group', )
    return export_data(request, UserGroup, UserGroupSchemaOut, export_fields)


# 导出
@router.post('/user_group/all/import')
def import_user_group(request, data: ImportSchema):
    import_fields = ('name', 'user_group', )
    return import_data(request, UserGroup, UserGroupSchemaIn, data, import_fields)
    